/**
 * 
 */

$(document).ready(function() {
	
	checkLoggedUser();
	
	// handle events
	$("#btn-user-login").click(function() {
		loginUser();
	});
	
	$("#btn-goto-register-user").click(function() {
	});
	
});

function checkLoggedUser() {
	var userId = $.getCookie("geoserverudima.userId");
	var sessionToken = $.getCookie("geoserverudima.sessionToken");
	
	if(userId != null && sessionToken != null) {
		$.ajax({
		    url : "../rest/users/validateUserSession",
		    type: "POST",
		    contentType: "application/json",
		    data : JSON.stringify({"userId": userId, "sessionToken": sessionToken}),
		    dataType: "json",
		    success: function(data, textStatus, jqXHR) {
		    	processUserAccessResult(data);
		    },
		    error: function (jqXHR, textStatus, errorThrown) {
		 
		    }
		});
	}
}

function loginUser() {
	var formData = $.formDataToJson($("#frmLogin"));
	$.ajax({
	    url : "../rest/users/login",
	    type: "POST",
	    contentType: "application/json",
	    data : formData,
	    dataType: "json",
	    success: function(data, textStatus, jqXHR) {
	        processUserLoginResult(data);
	    },
	    error: function (jqXHR, textStatus, errorThrown) {
	 
	    }
	});
}

function processUserLoginResult(ulr) {
	$("#div-user-login-error-user").hide();
	$("#div-user-login-error-password").hide();
	
	if(ulr.loginSuccessful){
		document.cookie = "geoserverudima.userId="+ulr.userSession.userId;
		document.cookie = "geoserverudima.sessionToken="+ulr.userSession.sessionToken;
		
		var redirect = 'mobileEmulator.jsp';
		$.redirectPost(redirect, {
					userId: ulr.userSession.userId, 
					sessionToken: ulr.userSession.sessionToken
				});
	} else {
		if($.inArray('EMPTY_USERNAME', ulr.loginErrors) >= 0) {
			$("#div-user-login-error-user").html("Complete el nombre de usuario").show();
		}
		
		if($.inArray('INCORRECT_USERNAME', ulr.loginErrors) >= 0) {
			$("#div-user-login-error-user").html("Nombre de usuario incorrecto").show();
		}
		
		if($.inArray('EMPTY_PASSWORD', ulr.loginErrors) >= 0) {
			$("#div-user-login-error-password").html("Complete la contraseña").show();
		}
		
		if($.inArray('INCORRECT_PASSWORD', ulr.loginErrors) >= 0) {
			$("#div-user-login-error-password").html("Contraseña incorrecta").show();
		}
	}
}

function processUserAccessResult(uar) {
	if(uar.accessSuccessful) {
		var redirect = 'mobileEmulator.jsp';
		$.redirectPost(redirect, null);
	} 
}

